package com.itmuch.icms.freemarker.directive;

import static freemarker.template.ObjectWrapper.DEFAULT_WRAPPER;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.itmuch.core.util.DozerUtil;
import com.itmuch.icms.channel.ChannelVo;
import com.itmuch.icms.channel.domain.Channel;
import com.itmuch.icms.channel.service.IChannelService;
import com.itmuch.icms.freemarker.directive.constants.DirectiveConstants;
import com.itmuch.icms.freemarker.directive.util.DirectiveUtils;
import com.itmuch.icms.util.UrlUtil;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 栏目列表标签
 * 作用：列表指定id的子栏目
 * 使用方法：详见readme_自定义标签.txt
 * @author ITMuch
 *
 */
public class ChannelListDirective implements TemplateDirectiveModel {

    @Resource
    private IChannelService channelService;

    @SuppressWarnings({ "unchecked", "rawtypes", "deprecation" })
    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {

        Integer id = DirectiveUtils.getInt(DirectiveConstants.ID, params);
        List<Channel> list = null;
        // 加载所有非单页的、并且display_flag=true的非单页栏目
        if (id == null) {
            list = this.channelService.selectTopChannels(true, false);
        }
        // 查询指定id下的所有子栏目
        else {
            list = this.channelService.selectChildChannelsById(id, true, false);
        }

        // 取得栏目地址
        List<ChannelVo> voList = new ArrayList<ChannelVo>();
        if ((list != null) && !list.isEmpty()) {
            for (Channel channel : list) {
                ChannelVo vo = DozerUtil.map(channel, ChannelVo.class);
                vo.setUrl(UrlUtil.getChannelUrl(channel.getId()));
                voList.add(vo);
            }
        }
        TemplateModel wrap = DEFAULT_WRAPPER.wrap(voList);
        env.setVariable(DirectiveConstants.CHANNEL_LIST, wrap);
        body.render(env.getOut());
    }
}